package yi.master.coretest.message.process.util.ysb;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
import com.cryptography.neu.sm.SM4;
import com.cryptography.neu.sm.SM4_Context;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2020/6/5 10:40
 */
public class YsbSM4Util {
    public static String decryptData_ECB(String cipherText, byte[] secretKey) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = 0;
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, secretKey);
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, (new BASE64Decoder()).decodeBuffer(cipherText));
            return new String(decrypted, "GBK");
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }

    public static String encryptData_ECB(String plainText, byte[] secretKey) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = 1;
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, secretKey);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes("GBK"));
            String cipherText = (new BASE64Encoder()).encode(encrypted);
            Matcher m = null;
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(cipherText);
            }

            return m.replaceAll("");
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }
}
